#include "profile.h"

#define MAX_CMD_LENGTH 200

extern char prompt[MAX_CMD_LENGTH];

void readProfile()
{
	int rc;
	char *i, *key, *value;
	char buffer[PROFILE_LINE_LENGTH];
	char localValue[PATH_SIZE];
	char *envVar;
	FILE *fp;

	fp = NULL;
	rc = -1;
	
  	/* Read the profile file and set the required environment variables */
 
	fp = fopen(PROFILE_FILE_NAME,"r");
	if (fp == NULL) {
		printf("Error opening profile file - Setting default values...\n");
		// return -1;
	}



	/* Setting default path */
	rc = setenv("PATH",DEFAULT_PATH,1);
	if (rc < 0 ) {
	   	perror("Setting default path failed");
	} 

	/* Setting default prompt sign  */
	strncpy(prompt,DEFAULT_PROMPT_SIGN,strlen(DEFAULT_PROMPT_SIGN));
        prompt[strlen(DEFAULT_PROMPT_SIGN)] = '\0';

    
	/* parse the file  and set the environment variables*/
	while(fp != NULL && fgets(buffer,PROFILE_LINE_LENGTH,fp)!= NULL) 
	{
		memset(localValue, 0, PATH_SIZE);
		if(strstr(buffer, "HOME") != NULL) 
		{
			key = strtok(buffer,"=");
			envVar = strtok(NULL,"=");
			strncpy(localValue, envVar, strlen(envVar) - 1);

			/*Set the environment variable*/
			rc = setenv(buffer,localValue, 1);
			rc = chdir(localValue);
			if (rc < 0 ) 
			{
				perror("Error");
				printf("Failed to change to local home directory %s %d\n", localValue, strlen(localValue));
			}
		
		}
		else if(strstr(buffer, "PROMPT") != NULL) 
		{
			key = strtok(buffer,"=");
			value = strtok(NULL,"=");
			strncpy(prompt,value,strlen(value) - 1);
			prompt[strlen(value) - 1] = '\0';
		}
		else if(strstr(buffer, "PATH") != NULL) 
		{
			key = strtok(buffer,"=");
			envVar = strtok(NULL,"=");
			strncpy(localValue, envVar, strlen(envVar) - 1);

			//printf("1) buffer = %s :: \n",buffer);
			//printf("2) localValue = %s :: \n",localValue);		
			/*Set the environment variable*/
			rc = setenv(buffer,localValue,1);
		} 
		memset(buffer,0,PROFILE_LINE_LENGTH);
		key = NULL;
		value = NULL;
	}
	if (fp != NULL) 
	{
	    fclose(fp);
	}

}


